package com.clei.netty.reconnect.client;

import com.clei.consts.NettyConstants;
import com.clei.utils.PrintUtil;
import com.clei.utils.StringUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * reconnect client handler
 *
 * @author KIyA
 */
public class ReconnectClientHandler extends SimpleChannelInboundHandler<String> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) {
        // 输出消息
        if (!StringUtil.isBlank(msg)) {
            String separator = NettyConstants.STR_SEPARATOR;
            int index = msg.indexOf(separator);
            if (index > 0) {
                String msgUserId = msg.substring(0, index);
                PrintUtil.log("[{}] - {}", msgUserId, msg.substring(index + separator.length()));
            } else {
                PrintUtil.log(msg);
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        PrintUtil.log("[{}]异常关闭", ctx.channel().remoteAddress(), cause);
        // 遇到异常就关闭连接
        ctx.close();
    }
}